package com.limeng.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MiniCatClassLoader extends ClassLoader {

    private String name;

    private File classFile;

    public MiniCatClassLoader() {
    }

    public MiniCatClassLoader(ClassLoader parent){
        super(parent);
        this.name = "MiniCatClassLoader";
    }

    public Class<?> findMiniClass(File file, String classFileName) throws ClassNotFoundException {
        this.classFile = file;
        System.out.println(classFileName+"==========");
        return findClass(classFileName);
    }

    @Override
    protected Class<?> findClass(String fileName) throws ClassNotFoundException {
        byte[] data = loadClassData(fileName);
        if(!fileName.endsWith(".class")){
            return null;
        }
        String className = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.indexOf(".class"));
        return this.defineClass(className, data, 0, data.length);
    }

    public byte[] loadClassData(String classFileName){
        try{
            if(!classFileName.endsWith(".class")){
                return null;
            }
            File file = new File(classFileName);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len = 0;
            while((len=fis.read())!=-1){
                bos.write(len);
            }
            return bos.toByteArray();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
